<template>
  <view class="container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-avatar">
        <u-avatar
          :src="userInfo.avatar || '/static/default-avatar.png'"
          size="120"
          mode="aspectFill"
        ></u-avatar>
      </view>
      <view class="user-info">
        <text class="username">{{ userInfo.username || '阅读爱好者' }}</text>
        <text class="user-desc">{{ userInfo.desc || '享受阅读的乐趣' }}</text>
      </view>
      <view class="edit-btn" @click="editProfile">
        <u-icon name="edit-pen" size="24" color="#007aff"></u-icon>
      </view>
    </view>

    <!-- 阅读统计 -->
    <view class="stats-section">
      <view class="stats-title">阅读统计</view>
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ readingStats.totalBooks }}</text>
          <text class="stat-label">总书籍</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ readingStats.totalWords }}</text>
          <text class="stat-label">总字数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ readingStats.readingTime }}</text>
          <text class="stat-label">阅读时长</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ readingStats.finishedBooks }}</text>
          <text class="stat-label">已读完</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-title">功能设置</view>
      
      <view class="menu-list">
        <view class="menu-item" @click="goToSettings">
          <view class="menu-icon">
            <u-icon name="setting" size="24" color="#007aff"></u-icon>
          </view>
          <text class="menu-text">阅读设置</text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
        
        <view class="menu-item" @click="exportData">
          <view class="menu-icon">
            <u-icon name="download" size="24" color="#34c759"></u-icon>
          </view>
          <text class="menu-text">导出数据</text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
        
        <view class="menu-item" @click="clearData">
          <view class="menu-icon">
            <u-icon name="trash" size="24" color="#ff3b30"></u-icon>
          </view>
          <text class="menu-text">清空数据</text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
        
        <view class="menu-item" @click="aboutApp">
          <view class="menu-icon">
            <u-icon name="info-circle" size="24" color="#ff9500"></u-icon>
          </view>
          <text class="menu-text">关于应用</text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>
    </view>

    <!-- 编辑资料弹窗 -->
    <u-popup v-model="showEditProfile" mode="center" width="90%" height="60%">
      <view class="edit-profile-popup">
        <view class="popup-header">
          <text class="popup-title">编辑资料</text>
          <u-icon name="close" size="24" @click="showEditProfile = false"></u-icon>
        </view>
        
        <view class="edit-form">
          <view class="form-item">
            <text class="form-label">用户名</text>
            <u-input 
              v-model="editForm.username" 
              placeholder="请输入用户名"
              border="surround"
            ></u-input>
          </view>
          
          <view class="form-item">
            <text class="form-label">个人简介</text>
            <textarea
              v-model="editForm.desc"
              class="desc-textarea"
              placeholder="请输入个人简介"
              :maxlength="100"
              style="min-height: 120rpx; width: 100%; border: 1px solid #e0e0e0; border-radius: 8rpx; padding: 20rpx; box-sizing: border-box;"
            ></textarea>
          </view>
        </view>
        
        <view class="popup-actions">
          <u-button @click="showEditProfile = false">取消</u-button>
          <u-button type="primary" @click="saveProfile">保存</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 自定义底部导航（list模式） -->
    <u-tabbar v-model="current" :list="tabBarList" :fixed="true" :placeholder="true" @change="onTabChange" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';

// 隐藏原生tabbar
onMounted(() => {
  uni.hideTabBar({ animation: false });
});

const current = ref(2);
onShow(() => {
  uni.hideTabBar({ animation: false });
  current.value = 2;
});

// 自定义tabbar配置
const tabBarList = ref([
  { iconPath: 'home', selectedIconPath: 'home-fill', text: '首页' },
  { iconPath: 'plus', selectedIconPath: 'plus', text: '导入', midButton: false },
  { iconPath: 'account', selectedIconPath: 'account-fill', text: '我的' }
]);

// 响应式数据
const showEditProfile = ref(false);
const userInfo = ref({
  username: '阅读爱好者',
  desc: '享受阅读的乐趣',
  avatar: ''
});
const editForm = ref({
  username: '',
  desc: ''
});

const readingStats = ref({
  totalBooks: 0,
  totalWords: 0,
  readingTime: '0小时',
  finishedBooks: 0
});

const editProfile = () => {
  editForm.value.username = userInfo.value.username;
  editForm.value.desc = userInfo.value.desc;
  showEditProfile.value = true;
};

const saveProfile = () => {
  if (!editForm.value.username.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' });
    return;
  }
  userInfo.value.username = editForm.value.username.trim();
  userInfo.value.desc = editForm.value.desc.trim();
  try {
    uni.setStorageSync('userInfo', userInfo.value);
    uni.showToast({ title: '保存成功', icon: 'success' });
    showEditProfile.value = false;
  } catch (e) {
    uni.showToast({ title: '保存失败', icon: 'none' });
  }
};

const goToSettings = () => {
  uni.showToast({ title: '功能开发中', icon: 'none' });
};

const exportData = () => {
  try {
    const books = uni.getStorageSync('books') || [];
    const data = { books, userInfo: userInfo.value, exportTime: new Date().toISOString() };
    const dataStr = JSON.stringify(data, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `reading-data-${new Date().toLocaleDateString()}.json`;
    link.click();
    URL.revokeObjectURL(url);
    uni.showToast({ title: '导出成功', icon: 'success' });
  } catch (e) {
    uni.showToast({ title: '导出失败', icon: 'none' });
  }
};

const clearData = () => {
  uni.showModal({
    title: '确认清空',
    content: '此操作将清空所有书籍和阅读记录，无法恢复！',
    confirmText: '确认清空',
    confirmColor: '#ff3b30',
    success: (res) => {
      if (res.confirm) {
        try {
          uni.removeStorageSync('books');
          uni.removeStorageSync('readingProgress');
          uni.showToast({ title: '数据已清空', icon: 'success' });
          uni.$emit('booksUpdated');
        } catch (e) {
          uni.showToast({ title: '清空失败', icon: 'none' });
        }
      }
    }
  });
};

const aboutApp = () => {
  uni.showModal({
    title: '关于应用',
    content: '小说阅读器 v1.0.0\n\n一个干净简洁的阅读应用，支持文本导入和本地阅读。\n\n特点：\n• 无广告干扰\n• 支持多种格式\n• 本地存储，保护隐私\n• 简洁美观的界面',
    showCancel: false,
    confirmText: '知道了'
  });
};

const formatWordCount = (count) => {
  if (count < 1000) return count;
  if (count < 10000) return (count / 1000).toFixed(1) + 'K';
  return (count / 10000).toFixed(1) + 'W';
};

const calculateReadingStats = () => {
  try {
    const books = uni.getStorageSync('books') || [];
    const progress = uni.getStorageSync('readingProgress') || {};
    let totalWords = 0;
    let finishedBooks = 0;
    books.forEach(book => {
      totalWords += book.wordCount || 0;
      if (progress[book.id] && progress[book.id] >= 100) finishedBooks++;
    });
    readingStats.value = {
      totalBooks: books.length,
      totalWords: formatWordCount(totalWords),
      readingTime: '0小时',
      finishedBooks
    };
  } catch (e) {}
};

onMounted(() => {
  calculateReadingStats();
});
uni.$on('booksUpdated', calculateReadingStats);

// 自定义tabbar切换
const onTabChange = (index) => {
  current.value = index;
  if (index === 0) {
    uni.switchTab({ url: '/pages/index/index' });
  } else if (index === 1) {
    uni.switchTab({ url: '/pages/import/import' });
  } else if (index === 2) {
    // 当前页
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  padding-bottom: 140rpx; // 预留自定义tabbar空间
  background-color: #f5f5f5;
  min-height: 100vh;
}

.user-card {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  position: relative;
  
  .user-avatar {
    margin-right: 30rpx;
  }
  
  .user-info {
    flex: 1;
    
    .username {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .user-desc {
      display: block;
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .edit-btn {
    padding: 20rpx;
  }
}

.stats-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .stats-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.stat-item {
  text-align: center;
  
  .stat-number {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #007aff;
    margin-bottom: 10rpx;
  }
  
  .stat-label {
    display: block;
    font-size: 24rpx;
    color: #666;
  }
}

.menu-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .menu-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.menu-list {
  .menu-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .menu-icon {
      margin-right: 20rpx;
    }
    
    .menu-text {
      flex: 1;
      font-size: 30rpx;
      color: #333;
    }
  }
}

.edit-profile-popup {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .edit-form {
    margin-bottom: 30rpx;
    
    .form-item {
      margin-bottom: 20rpx;
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
    }
  }
  
  .popup-actions {
    display: flex;
    gap: 20rpx;
    
    .u-button {
      flex: 1;
    }
  }
}

.desc-textarea {
  font-size: 28rpx;
  line-height: 1.6;
  resize: none;
}
</style>
